import React, { Component } from 'react'
import './form.scss'
import PropTypes from 'prop-types';
import View from './../view/view'

/* root:
1，先写好blur的valiedate
2，再在form里forEach全部validate，如果有一个返回false就不通过
*/

export default class FormItem extends Component {
  constructor (props) {
    super(props)
    this.state = {
      showErrorTip: false
    }
    this.getValue = this.getValue.bind(this)
    this.onInputBlur = this.onInputBlur.bind(this)
    this.validate = this.validate.bind(this)
  }
  getChildContext () {
    return {
      FormItem: this
    }
  }
  Form () {
    return this.context.Form
  }
  onInputChange () {
  }
  onInputBlur () {
    this.validate()
  }
  getValue () {
    return this.Form().getFormData()[this.props.prop]
  }
  resetValidate () {
    this.setState({
      showErrorTip: false
    })
  }
  validate () {
    if (this.props.rules === 'required') {
      const isPass = this.getValue() !== ''
      this.setState({
        showErrorTip: !isPass
      })
      return isPass
    } else {
      return true
    }
  }
  componentDidMount () {
    this.Form().addItem(this)
  }
  render () {
    return (
      <div className="tbcFormItem">
        <div className="tbcFormItemLabel">{this.props.label}</div>
        <div className="tbcFormItemSlot">
          {this.props.children}
          <View show={this.state.showErrorTip} name="fade-in">
            <div className="tbcFormItemRelus">必填</div>
          </View>
        </div>
      </div>
    )
  }
}

FormItem.contextTypes = {
  Form: PropTypes.any
}

FormItem.childContextTypes = {
  FormItem: PropTypes.any
}